package cn.topevery.garden.wapi.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.topevery.garden.dal.logic.*;
import cn.topevery.garden.entity.po.Person;
import cn.topevery.garden.entity.po.PersonSearch;
import cn.topevery.garden.entity.po.TaskPersonRelation;
import cn.topevery.garden.entity.query.PersonQuery;
import cn.topevery.garden.entity.vo.PersonVO;
import cn.topevery.garden.wapi.config.GreProperties;
import com.github.dozermapper.core.Mapper;
import hw.topevery.basis.dal.logic.SysUserLogic;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author code-generate
 * @date 2021-08-06
 */
@Api(tags = "")
@RestController
@RequestMapping("/person")
public class PersonController extends BaseController {


    @Autowired
    PersonLogic personLogic;

    @Autowired
    ParkLogic parkLogic;

    @Autowired
    SectionLogic sectionLogic;

    @Autowired
    PersonClassLogic personClassLogic;

    @Autowired
    ExtentLogic extentLogic;

    @Autowired
    SysUserLogic sysUserLogic;

    @Autowired
    GreProperties greProperties;

    @Autowired
    private Mapper mapper;

    @Autowired
    private TaskPersonRelationLogic relationLogic;

    /**
     * 获取分页列表
     *
     * @param query
     * @return
     */
    @ApiOperation(value = "获取页列表")
    @PostMapping("/getList")
    public JsonResult<DataPager<PersonSearch>> listPage(@RequestBody PersonQuery query) {
        SysUser user = getUser();
        query.setDeptId(user.userIsAdmin == 1 ? null : user.deptId);
        return JsonResult.ok(personLogic.listPage(query));
    }

    private SysUser fillSysUser(SysUser sysUser, PersonVO personVO) throws Exception {
        if (sysUser == null) {
            String key = greProperties.rsaPublicKey.trim();
            sysUser = new SysUser();
            String userId = UUID.randomUUID().toString().toLowerCase();
            personVO.userId = userId;
            //用户名为手机号
            //密码为park@+手机号后四位
            sysUser = new SysUser();
            sysUser.userType = 11002;
            sysUser.userId = userId;
            sysUser.loginName = personVO.getUserMobile();
            sysUser.deptId = "";
            sysUser.mapType = 0;
            sysUser.mapId = "";
            sysUser.userIsAdmin = 0;
            sysUser.orderNum = 0;
            String input = "";
            if (StringUtils.isNotBlank(personVO.getUserMobile())) {
                input = "park@" + personVO.getUserMobile().substring(personVO.getUserMobile().length() - 4);
            }
            /*PasswordEncoder encoder = new BCryptPasswordEncoder(10);
            String encoderPwd = encoder.encode(input);
            sysUser.loginPassword = encoderPwd;*/
        }

        if (!Strings.isBlank(personVO.getImgFileId())) {
            sysUser.imageUrl = personVO.getImgFileId();
        }
        if (!Strings.isBlank(personVO.getName())) {
            sysUser.userName = personVO.getName();
        }
        if (!Strings.isBlank(personVO.getUserMobile())) {
            if (StringUtils.isBlank(sysUser.loginName)) {
                sysUser.loginName = personVO.getUserMobile();
            }
            sysUser.userMobile = personVO.getUserMobile();
        }
        if (!Strings.isBlank(personVO.getUserIdcard())) {
            sysUser.userIdcard = personVO.getUserIdcard();
        }
        if (personVO.getUserSex() == null) {
            sysUser.userSex = 1;
        } else {
            sysUser.userSex = Byte.parseByte(personVO.getUserSex().toString());
        }
        if (personVO.getUserBirthday() != null) {
            sysUser.userBirthday = personVO.getUserBirthday();
        }
        if (!Strings.isBlank(personVO.getDeptId())) {
            sysUser.deptId = personVO.getDeptId();
        }
        return sysUser;
    }

    @ApiOperation("导入数据")
    @PostMapping("/importExcel")
    public JsonResult<Boolean> importExcel(@RequestBody MultipartFile file) throws Exception {
        JsonResult<Boolean> res = new JsonResult<Boolean>();
        try {
            ImportParams importParams = new ImportParams();
            importParams.setHeadRows(1);
            importParams.setNeedVerify(true);
            ExcelImportResult<PersonVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), PersonVO.class, importParams);
            List<PersonVO> personVOList = result.getList();
            if (personVOList.size() > 0) {
                personVOList.forEach(param -> {
                    try {
                        SysUser sysUser = null;
                        if (StringUtils.isNotBlank(param.userId)) {
                            sysUser = sysUserLogic.getEntityByDataId(param.userId);
                        }
                        sysUser = fillSysUser(sysUser, param);
                        if (sysUser.id != null && sysUser.id > 0) {
                            sysUserLogic.update(getUser().id.toString(), sysUser);
                        } else {
                            sysUserLogic.save(getUser().id.toString(), sysUser);
                        }
                        Person person = mapper.map(param, Person.class);
                        personLogic.saveOrUpdate(getUser().id.toString(), person);
                        if (param.getTaskId() != null && param.getTaskId() > 0) {
                            TaskPersonRelation taskPersonRelation = relationLogic.getByTaskId(param.getTaskId());
                            if (taskPersonRelation == null || !person.getId().equals(taskPersonRelation.getPersonId())) {
                                relationLogic.deleteByTaskId(getUser().id, param.getTaskId());
                                TaskPersonRelation relation = new TaskPersonRelation();
                                relation.setPersonId(person.getId());
                                relation.setPersonName(person.getName());
                                relation.setTaskId(param.getTaskId());
                                relationLogic.saveOrUpdate(getUser().id.toString(), relation);
                            }
                        } else {
                            relationLogic.deleteByUserId(getUser().id);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
                res.success = true;
            } else {
                res.success = false;
                res.msg = "未找到要导入的数据!";
            }

        } catch (Exception ex) {
            res.success = false;
            res.msg = "导入失败" + ex.getMessage();
        }
        return res;
    }

    @ApiOperation("新增/编辑 信息")
    @PostMapping("/save")
    public JsonResult<Boolean> saveOrUpdate(@Valid @RequestBody PersonVO param) throws Exception {

        SysUser sysUser = null;
        if (StringUtils.isNotBlank(param.userId)) {
            sysUser = sysUserLogic.getEntityByDataId(param.userId);
        }
        sysUser = fillSysUser(sysUser, param);
        if (sysUser.id != null && sysUser.id > 0) {
            sysUserLogic.update(getUser().id.toString(), sysUser);
        } else {
            sysUserLogic.save(getUser().id.toString(), sysUser);
        }
        Person person = mapper.map(param, Person.class);
        personLogic.saveOrUpdate(getUser().id.toString(), person);
        if (param.getTaskId() != null && param.getTaskId() > 0) {
            TaskPersonRelation taskPersonRelation = relationLogic.getByTaskId(param.getTaskId());
            if (taskPersonRelation == null || !person.getId().equals(taskPersonRelation.getPersonId())) {
                relationLogic.deleteByTaskId(getUser().id, param.getTaskId());
                TaskPersonRelation relation = new TaskPersonRelation();
                relation.setPersonId(person.getId());
                relation.setPersonName(person.getName());
                relation.setTaskId(param.getTaskId());
                relationLogic.saveOrUpdate(getUser().id.toString(), relation);
            }
        } else {
            relationLogic.deleteByUserId(getUser().id);
        }
        return JsonResult.ok(true);
    }

    @ApiOperation("获取详情")
    @GetMapping("/getInfoById")
    public JsonResult getInfoById(@RequestParam Integer id) {
        Person person = personLogic.getEntity(id);
        PersonVO personVo = mapper.map(person, PersonVO.class);
        if (StringUtils.isNotBlank(person.userId)) {
            SysUser sysUser = sysUserLogic.getEntityByDataId(person.userId);
            if (sysUser != null) {
                personVo.setUserMobile(sysUser.userMobile);
                personVo.setUserBirthday(sysUser.userBirthday);
                personVo.setUserIdcard(sysUser.userIdcard);
                personVo.setUserSex(Byte.toUnsignedInt(sysUser.userSex));
                personVo.setImgFileId(sysUser.imageUrl);
                personVo.setDeptId(sysUser.deptId);
            }
            TaskPersonRelation relation = relationLogic.getByPersonId(id);
            if (relation != null) {
                personVo.setTaskId(relation.getTaskId());
            }
        }
        return JsonResult.ok(personVo);
    }

    @ApiOperation("通过userId获取详情")
    @GetMapping("/getInfoByUserId")
    public JsonResult<?> getInfoByUserId(String userId) {
        PersonVO personVO = personLogic.getByUserId(userId);
        SysUser sysUser = sysUserLogic.getEntityByDataId(personVO.userId);
        personVO.setUserMobile(sysUser.userMobile);
        personVO.setUserBirthday(sysUser.userBirthday);
        personVO.setUserIdcard(sysUser.userIdcard);
        personVO.setUserSex(Byte.toUnsignedInt(sysUser.userSex));
        personVO.setImgFileId(sysUser.imageUrl);
        TaskPersonRelation relation = relationLogic.getByPersonId(personVO.getId());
        if (relation != null) {
            personVO.setTaskId(relation.getTaskId());
        }
        return JsonResult.ok(personVO);
    }

    @ApiOperation("根据自增ID批量删除")
    @GetMapping("/deleteInfoByIds")
    public JsonResult<Boolean> deleteBatchById(@RequestParam Integer[] ids) {
        List<SysUser> sysUsers = new ArrayList<>();
        for (Integer id :
                ids) {
            Person person = personLogic.getEntity(id);
            if (person != null && StringUtils.isNotBlank(person.getUserId())) {
                SysUser sysUser = sysUserLogic.getEntityByDataId(person.getUserId());
                if (sysUser != null && sysUser.id > 0) {
                    sysUsers.add(sysUser);
                }
            }
        }
        sysUserLogic.deleteUser(getUser().userId, sysUsers);
        personLogic.deleteBatchById(getUser().id.toString(), ids);
        return JsonResult.ok(true);
    }

//    @ApiOperation("导入数据")
//    @PostMapping("/importExcel")
//    public JsonResult<Boolean> importExcel(@RequestBody MultipartFile file) throws Exception {
//        JsonResult<Boolean> res = new JsonResult<Boolean>();
//        try {
//            ImportParams importParams = new ImportParams();
//            importParams.setHeadRows(1);
//            importParams.setNeedVerify(true);
//            ExcelImportResult<PersonVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), PersonVO.class, importParams);
//            List<PersonVO> personVOList = result.getList();
//
//            if(result.getFailList().size()>0){
//                res.success=false;
//                res.msg="校验存在不通过的数据行:"+String.join(",",result.getFailList().stream().map(PersonVO::getName).collect(Collectors.toList()));
//            }
//            else {
//                if(personVOList.size()>0) {
//                    //批量导入队列
//                    List<SysUser> sysUsers = new ArrayList<>();
//                    List<Person> personList = new ArrayList<>();
//
//                    //根据手机号集合查找人员与pmi用户集合
//                    List<String> mobiles=personVOList.stream().map(PersonVO::getUserMobile).collect(Collectors.toList());
//                    List<Person> userListByMobile=personLogic.getPesonList(mobiles);
//                    List<SysUser> pesonListByMobile=personLogic.getSysUserList(mobiles);
//
//                    //需要参与转换的数据源
//                    Map<String, Integer> sectionDic = DataUtils.ToMap(sectionLogic.getShortList(), "name", "id");
//                    Map<String, Integer> parkDic = DataUtils.ToMap(parkLogic.getShortList(), "name", "id");
//                    Map<String, Integer> personClassDic = DataUtils.ToMap(personClassLogic.getOptions(), "name", "id");
//                    ExtentQuery extentQuery = new ExtentQuery();
//                    Map<String, Integer> extentDic = DataUtils.ToMap(extentLogic.options(extentQuery), "name", "id");
//                    Map<Integer, String> workStateDic = DataUtils.getAnnotationExcelReplace(PersonVO.class, "workState");
//
//                    personVOList.forEach(f -> {
//                        try {
//                            SysUser sysUser=pesonListByMobile.stream().filter(ff->ff.userMobile.equals(f.getUserMobile())).findFirst().get();
//                            Person person=userListByMobile.stream().filter(ff->ff.userId.equals(sysUser.userId)).findFirst().get();
//                            if(person==null){
//                                person=new Person();
//                            }
//                            if (personClassDic.containsKey(f.getTypeName())) {
//                                person.typeName=f.getTypeName();
//                                person.type=personClassDic.get(f.getTypeName());
//                            }
//                            if (sectionDic.containsKey(f.getSectionName())) {
//                                person.sectionId=sectionDic.get(f.getSectionName());
//                                person.sectionName=f.getSectionName();
//                            }
//                            if (parkDic.containsKey(f.getParkName())) {
//                                person.parkName=f.getParkName();
//                                person.parkId=parkDic.get(f.getParkName());
//                            }
//                            if (workStateDic.containsKey(f.workState)) {
//                                person.workState=f.workState;
//                                person.workStateDesc=workStateDic.get(f.workState);
//                            }
//                            if (extentDic.containsKey(f.getExtentName())) {
//                                person.extentName=f.getExtentName();
//                                person.extentId=extentDic.get(f.getExtentName());
//                            }
//                            //字典类数据转换
//                            sysUsers.add(fillSysUser(sysUser, f));
//                            personList.add(person);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    });
//                    List<SysUser> insertSysUsers=sysUsers.stream().filter(f->f.id==null||f.id.equals(0)).collect(Collectors.toList());
//                    List<SysUser> updateSysUsers=sysUsers.stream().filter(f->f.id!=null&&f.id>0).collect(Collectors.toList());
//                    if(insertSysUsers.size()>0) {
//                        sysUserLogic.insert(getUser().userId, insertSysUsers);
//                    }
//                    if(updateSysUsers.size()>0) {
//                        sysUserLogic.update(getUser().userId, updateSysUsers);
//                    }
//                    List<Person> insertPerson=personList.stream().filter(f->f.id==null||f.id.equals(0)).collect(Collectors.toList());
//                    List<Person> updatePerson=personList.stream().filter(f->f.id!=null&&f.id>0).collect(Collectors.toList());
//                    if(insertPerson.size()>0) {
//                        personLogic.insert(getUser().id.toString(),insertPerson);
//                    }
//                    if(updatePerson.size()>0) {
//                        personLogic.update(getUser().id.toString(), updatePerson);
//                    }
//                    res.success = true;
//                }
//                else{
//                    res.success=false;
//                    res.msg="未找到要导入的数据!";
//                }
//            }
//        }
//        catch (Exception ex){
//            res.success=false;
//            res.msg="导入失败"+ex.getMessage();
//        }
//        return  res;
//    }


    @ApiOperation("导出信息")
    @GetMapping("/export")
    public void export(PersonQuery query, HttpServletResponse response) {
        List<PersonSearch> list = personLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "", "sheet1", Person.class, "", response);
    }

}
